<template>
  <div>
    <h1>实时语音对话</h1>
    <button @click="startRecording" :disabled="isRecording">开始录音</button>
    <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
    <button @click="playAudio" :disabled="!audioBlob">播放接收的音频</button>
  </div>
</template>

<script>
export default {
  name:"audio-test",
  data() {
    return {
      isRecording: false,
      mediaRecorder: null,
      audioChunks: [],
      audioBlob: null,
      socket: null,
    };
  },
  methods: {
    // 初始化录音
    async startRecording() {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        this.mediaRecorder = new MediaRecorder(stream);
        this.mediaRecorder.ondataavailable = (event) => {
          console.log("ondataavailable",event)
          this.audioChunks.push(event.data);
        };
        this.mediaRecorder.onstop = () => {
          console.log("this.audioChunks",this.audioChunks)
          const audioBlob = new Blob(this.audioChunks, { type: "audio/wav" });
          this.audioChunks = [];
          this.sendAudioToServer(audioBlob);
        };
        this.mediaRecorder.start();
        this.isRecording = true;
      } catch (error) {
        console.error("无法访问麦克风:", error);
      }
    },

    // 停止录音
    stopRecording() {
      if (this.mediaRecorder) {
        this.mediaRecorder.stop();
        this.isRecording = false;
      }
    },

    // 发送音频数据到服务器
    sendAudioToServer(audioBlob) {
      if (this.socket) {
        console.log("audioBlob",audioBlob)
        // this.socket.send(audioBlob);
      }
    },

    // 播放接收的音频
    playAudio() {
      if (this.audioBlob) {
        const audioUrl = URL.createObjectURL(this.audioBlob);
        const audio = new Audio(audioUrl);
        audio.play();
      }
    },

    // 初始化 WebSocket
    initWebSocket() {
      this.socket = new WebSocket("ws://your-server-url");

      this.socket.onmessage = (event) => {
        const audioBlob = new Blob([event.data], { type: "audio/wav" });
        this.audioBlob = audioBlob;
      };

      this.socket.onopen = () => {
        console.log("WebSocket 连接成功");
      };

      this.socket.onclose = () => {
        console.log("WebSocket 连接关闭");
      };
    },
  },
  mounted() {
    // this.initWebSocket();
  },
  beforeDestroy() {
    if (this.socket) {
      this.socket.close();
    }
  },
};
</script>